<template>
  <div class="update-photo">
    <img :src="img" ref="img">
    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>
<script>
// https://github.com/fengyuanchen/cropperjs  图片裁剪插件
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
import {updateUserPhotoAPI} from '@/api';


export default {

  name:"UpdatePhoto",
  components:{},
  props:{
    img:{
      type:[String,Object],
      required:true
    }
  },
  data(){
    return {
      cropper:null
    }
  },
  computed:{},
  watch:{},
  mounted(){
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,  //裁剪区是否可以超出裁剪范围
      dragMode: 'move',   //拖动模式
      aspectRatio: 1,  //截图比例  1:1
      autoCropArea: 1,  //自动截图区 默认1:1
      cropBoxMovable: false,  //截图区是否可以移动
      cropBoxResizable: false,  //截图区是否可以缩放
      background: false,  //是否开启背景
      movable: true  //画布是否可以移动
    })
  },
  methods:{
    onConfirm(){
      // console.log(this.cropper.getData())   //获取裁剪参数  基于服务端裁剪可以把参数传过去
      // console.log(this.cropper.getCroppedCanvas())  //获取裁剪之后的图像对象(类似于window.URL.creatObjectURL得到的文件对象)
      this.cropper.getCroppedCanvas().toBlob( blob=>{
        this.updateUserPhoto(blob)
      })
    },
    async updateUserPhoto(blob){
      this.$toast.loading({
        message:'上传中...',
        forbidClick:true,
        duration:0
      })
      const formData=new FormData()
        formData.append('photo',blob)
        try{
          const {data}=await updateUserPhotoAPI(formData)
          this.$emit('update-photo',data.data.photo)
          this.$toast.success('头像上传成功!')
        }catch(err){
          this.$toast.fail('头像上传失败!')
        }
        this.$emit('close')
    }
  }
}
</script>
<style lang="less" scoped>
.update-photo{
  background-color: #000;
  height: 100%;
  .toolbar{
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,.confirm{
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
  img {
    max-width: 100%;
    display: block;
  }
}

</style>